// 1.引入模块express
const express=require('express');
// 2，引入连接池
const pool = require('../pool.js');

// 3.因为要打包暴露出去所以要创建一个路由对象
let router=express.Router();
// ****************接口逻辑*************
router.post('/register', (req, res) => {
  //console.log(md5('12345678'));
  // 获取用户名和密码信息
  console.log(req.body);
  // console.log(req.body.username);
  // console.log(req.body.password);
  let username = req.body.username;
  let password = req.body.password;
  let userphone = req.body.userphone;
  // //以username为条件进行查找操作，以保证用户名的唯一性
  let sql = 'SELECT COUNT(uid) AS count FROM user WHERE uname=?';
  pool.query(sql, [username], (error, results) => {
    if (error) throw error;
    let count = results[0].count;
    if (count == 0) {
      // 将用户的相关信息插入到数据表
      sql = 'INSERT user(uname,upwd,uphone) VALUES(?,MD5(?),?)';
      pool.query(sql, [username, password,userphone], (error, results) => {
        if (error) throw error;
        res.send({ message: 'ok', code: 200 });
      })
    } else {
      res.send({ message: 'user exists', code: 201 });
    }
  });
});
// *************************************
router.post('/login', (req, res) => {
  //获取用户名和密码信息
  let username = req.body.username;
  let password = req.body.password;
  // SQL语句
  let sql = 'SELECT uid,uname FROM user WHERE uname=? AND upwd=MD5(?)';
  pool.query(sql, [username, password], (error, results) => {
    if (error) throw error;
    if(results.length == 0){ //登录失败
      res.send({message:'login failed',code:201});
    } else {                 //登录成功
      res.send({message:'ok',code:200,result:results[0]});
    }
  });

});
router.get('/us',(req,res)=>{
   let sql = 'SELECT * from user';
   pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({ message: 'ok', code: 200, results: results });
  });

})
// ***********************************
// 4.暴露路由（user）对象
module.exports=router;